import { createRouter, createWebHistory } from 'vue-router'
import type { App } from 'vue'
import { ref } from 'vue'
import { loadComponent } from '@/component.js'

import { getRouters } from '@/api'

const basicRoutes = {
  'LoginView': () => import('@/views/LoginView.vue'),
  'HomeView': () => import('@/views/LoginView.vue'),
  'AuthView': () => import('@/views/AuthView.vue'),
  'ErrorView': () => import('@/views/ErrorView.vue')
}


const router = createRouter({
  history: createWebHistory(),
  routes: [
    {
      path: '/',
      component: () => import('@/views/HomeView.vue')
    },
    {
      path:'/auth',
      component: () => import('@/views/AuthView.vue')
    },
    {
      path:'/login',
      component: () => import('@/views/LoginView.vue')
    },
    {
      path:"/error",
      component: () => import('@/views/ErrorView.vue')
    },
    {
      path: '/product',
      component: () => import('@/views/ClothesProductView.vue')
    },
    {
      path: '/search',
      component: () => import('@/views/SearchView.vue')
    }
  ]
})

const setupRouter = (app: App) => {
  app.use(router)
}

export { setupRouter, router }

router.beforeEach(async (to)=>{
  if(router.getRoutes().some((route:any) => route.path === to.path)){
    return
  }

  if(!router.getRoutes().some((route:any) => route.path === to.path)) {
    try {
      const res = await setDynamicRoutes({ web: to.path });
      if (!res) {
        // 如果设置不成功，直接跳转到错误页面
        await router.push('/error');
        return false;
      }
      await router.push(to.path);
    } catch (err) {
      await router.push('/error');
      return false
    }
  }
  await router.push(to)
})

// 可以尝试将动态路由的import换成glob，明天改，电不够了
export const setDynamicRoutes = async (web={}) => {
  try{
    const { data } = await getRouters(web)
    if(data === null || data.length===0){
      return false;
    }
    data.forEach((item:any) => {
      const route = {
            path: item.path,
            name: item.name,
            component: () => import((`../views/${item.component}.vue`)),
            children:[]
          }
      router.addRoute(route)

      item.children.forEach((child:any)=>{
        const childRoute = {
          path: child.path,
          name: child.name,
          component: () => import((`../views/${child.component}.vue`)),
        }
        route.children.push(childRoute)
      })
    })
    return true
  }catch (e){
    console.error("Failed to set dynamic routes:", e)
    return false
  }
}


export const pushRoute = (route:string) => {
  router.push(route)
}



